package io.argin.service.impl;

import io.argin.mapper.DeptMapper;
import io.argin.mapper.EmpMapper;
import io.argin.pojo.Dept;
import io.argin.pojo.Emp;
import io.argin.service.QueryService;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Service
public class QueryServiceImpl implements QueryService {
    @Resource
    private EmpMapper empMapper;
    @Resource
    private DeptMapper deptMapper;

    @Override
    public void insertEmp(Emp emp) {
        empMapper.insertSelective(emp);
    }

    @Override
    public void deleteEmp(Integer id) {
        empMapper.deleteByExample(id);
    }

    @Override
    public void updateEmp(Emp emp) {
        empMapper.updateByPrimaryKeySelective(emp);
    }

    @Override
    public Emp getEmp(Integer id) {
        return empMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Emp> listEmps(String name) {
        name = name == null ? "%" : "%" + name + "%";
        Example example = new Example(Emp.class);
        example.createCriteria()
                .andLike("name", name);
        List<Emp> empList = empMapper.selectByExample(example);
        this.handlerList(empList, deptMapper.select(null));
        return empList;
    }

    @Override
    public List<Dept> listDepts() {
        return deptMapper.select(null);
    }

    public void handlerList(List<Emp> empList, List<Dept> deptList) {
        // 先便历两个集合
        empList.forEach(emp -> deptList.forEach(dept -> {
            // 如果Emp的did和Dept的id相等
            if (emp.getDid().equals(dept.getId())) {
                // 那么就把Dept的name的值赋给给Emp的dept
                emp.setDept(dept.getName());
            }
        }));
    }
}
